//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package testcase_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type _CaseRecycleDao struct {
	mc *mongo.Collection
}

func newCaseRecycleDao(db *mongo.Database) (*_CaseRecycleDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_TEST_CASE + "case_recycle")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_CaseRecycleDao{mc: mc}, nil
}

func (db *_CaseRecycleDao) Insert(ctx context.Context, dbItem *CaseInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CaseRecycleDao) Get(ctx context.Context, caseId, projectId string) (*CaseInfoDbItem, error) {
	retItem := &CaseInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": caseId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_CaseRecycleDao) Remove(ctx context.Context, caseId, projectId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": caseId, "projectId": projectId})
	return err
}

func (db *_CaseRecycleDao) ListById(ctx context.Context, projectId string, caseIdList []string) ([]*CaseInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": caseIdList}, "projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []*CaseInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_CaseRecycleDao) DistinctIdByProject(ctx context.Context, projectId string) ([]string, error) {
	tmpList, err := db.mc.Distinct(ctx, "_id", bson.M{"projectId": projectId})
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, tmpValue := range tmpList {
		if tmpValue.(string) != "" {
			retList = append(retList, tmpValue.(string))
		}
	}
	return retList, nil
}
